<template>
  <input
    type="text"
    class="inp"
    :value="value"
    @input="handleInput"
    :class="{ success: state === 'success', error: state === 'error' }"
    @blur="blurFn"
  />
</template>

<script>
export default {
  data() {
    return {
      state: "",
    };
  },
  props: {
    value: String,
    rules: RegExp,
    msg: {
      type: String,
      default: "输入的数据不合法",
    },
  },
  methods: {
    handleInput(e) {
      // e.target 触发事件真实 DOM 节点
      // console.log(e.target.value)
      const v = e.target.value;
      this.$emit("input", v);
    },
    blurFn(e) {
      const str = e.target.value.trim();
      if (this.rules) {
        // 正则对象.test(字符串)        可以用来校验数据
        // 如果有传入表达式，undefined 是调用 .test() 会报错，所以加一层判断
        if (this.rules.test(str)) {
          // console.log(this.rules, str, "校验通过");
          this.state = "success";
        } else {
          // console.log(this.rules, str, "正则校验失败", this.msg);
          // this.$toast(this.msg)
          this.$notify({ type: "danger", message: this.msg, duration: 1000 });
          this.state = "error";
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.inp {
  width: 318px;
  height: 48px;
  font-size: 20px;
  border: none;
  outline: none;
  border-bottom: 2px solid #ccc;
  margin: 20px auto;
  display: block;
  background-color: transparent;
}
.success {
  border-bottom-color: green;
  //   color: #0a0;
}
.error {
  border-bottom-color: red;
  //   color: red;
}
</style>